import { useEffect } from 'react'
import { Modal, Form, Input, Message } from '@arco-design/web-react'
import { createWorkflow, updateWorkflow } from '@/api/workflow'
import type { WorkflowDefinition } from '@/types'

const FormItem = Form.Item

interface WorkflowFormModalProps {
  visible: boolean
  workflow?: WorkflowDefinition | null
  onCancel: () => void
  onSuccess: () => void
}

export default function WorkflowFormModal({
  visible,
  workflow,
  onCancel,
  onSuccess,
}: WorkflowFormModalProps) {
  const [form] = Form.useForm()
  const isEdit = !!workflow

  useEffect(() => {
    if (visible && workflow) {
      form.setFieldsValue({
        name: workflow.name,
        description: workflow.description,
        version: workflow.version,
      })
    } else if (visible) {
      form.resetFields()
    }
  }, [visible, workflow, form])

  const handleSubmit = async () => {
    try {
      const values = await form.validate()

      if (isEdit && workflow) {
        await updateWorkflow(workflow.id, values)
        Message.success('工作流更新成功')
      } else {
        await createWorkflow({
          ...values,
          stages: [], // 初始为空，后续可编辑
        })
        Message.success('工作流创建成功')
      }

      form.resetFields()
      onSuccess()
    } catch (error) {
      console.error('Failed to save workflow:', error)
    }
  }

  return (
    <Modal
      title={isEdit ? '编辑工作流' : '创建工作流'}
      visible={visible}
      onOk={handleSubmit}
      onCancel={() => {
        form.resetFields()
        onCancel()
      }}
      autoFocus={false}
      focusLock={true}
      okText="确定"
      cancelText="取消"
    >
      <Form
        form={form}
        layout="vertical"
        autoComplete="off"
      >
        <FormItem
          label="工作流名称"
          field="name"
          rules={[
            { required: true, message: '请输入工作流名称' },
            { minLength: 2, message: '名称至少2个字符' },
            { maxLength: 50, message: '名称最多50个字符' },
          ]}
        >
          <Input placeholder="请输入工作流名称" />
        </FormItem>

        <FormItem
          label="描述"
          field="description"
          rules={[{ maxLength: 200, message: '描述最多200个字符' }]}
        >
          <Input.TextArea
            placeholder="请输入工作流描述"
            rows={3}
            showWordLimit
            maxLength={200}
          />
        </FormItem>

        <FormItem
          label="版本"
          field="version"
          rules={[
            { required: true, message: '请输入版本号' },
            {
              match: /^\d+\.\d+\.\d+$/,
              message: '版本号格式错误，例如：1.0.0',
            },
          ]}
          initialValue="1.0.0"
        >
          <Input placeholder="1.0.0" />
        </FormItem>
      </Form>
    </Modal>
  )
}
